import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Applet } from 'src/entities/Applet';
import { AppletModelService } from 'src/model/applet-model/applet-model.service';
import { RedisService } from 'src/redis/redis.service';

@Injectable()
export class AppletService {
    private appletKey:string;
    constructor(
        private redis:RedisService,
        private appletModelService:AppletModelService,
        private configService:ConfigService
    ) {
        this.appletKey = this.configService.get<string>('cacheKey.applet')
    }

    async applet(type:number) {
        const key = this.appletKey + type
        let applet = await this.redis.get<Applet>(key)
        if(!applet) {
            applet = await this.appletModelService.findOne({type : type}, ['appid', 'appSecret', 'mchid', 'notifyUrl', 'serialNo', 'v3apiSecret', 'privateKey'])
            if(applet) {
                this.redis.set(key, applet, 'EX', 3600 * 24)
            }
        }

        return applet
    }
}
